package com.sneakxy.cloudbase.platform.http;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.session.web.http.DefaultCookieSerializer;

public class CloudBaseCookieSerializer extends DefaultCookieSerializer {

	@Autowired(required = false)
	private CookieValueHandler[] cookieValueHandlers;
	
	@Override
	public List<String> readCookieValues(HttpServletRequest request) {
		List<String> result = new ArrayList<>();
		if(cookieValueHandlers != null) {
			for(CookieValueHandler cookieValueHandler: cookieValueHandlers) {
				final List<String> sessionIds = cookieValueHandler.readCookieValues(request);
				if(sessionIds != null && !sessionIds.isEmpty()) {
					result.addAll(sessionIds);
				}
			}
		}
		result.addAll(super.readCookieValues(request));
		return result;
	}

	@Override
	public void writeCookieValue(CookieValue cookieValue) {
		super.writeCookieValue(cookieValue);
		if(cookieValueHandlers != null) {
			for(CookieValueHandler cookieValueHandler: cookieValueHandlers) {
				cookieValueHandler.writeCookieValue(cookieValue);
			}
		}
	}
	
}
